package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Menu;
import com.letv.whatslive.model.convert.MenuConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 视频分类dao
 * Created by wangjian on 2015-11-09.
 */
@Repository
public class MenuDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(MenuDAO.class);

    protected String collectionName = "menu";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    /**
     * 根据分类ID查询分类信息
     * @param id
     * @return 查询不到返回null
     */
    public Menu getMenuById(Long id){
        DBObject dbObject = new BasicDBObject();
        dbObject.put("_id", id);
        DBObject result = dbCollection.findOne(dbObject);
        if (result == null) {
            return null;
        }
        Menu menu = MenuConvert.castDBObjectToMenu(result);
        return menu;
    }

    /**
     * 插入视频分类信息
     * @param menu
     */
    public long insertMenu(Menu menu){
        DBObject obj = MenuConvert.castMenuToDBObject(menu);
        return this.insert(obj);
    }

    /**
     * 更新视频分类信息
     * @param menu
     */
    public void updateMenu(Menu menu) {
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", menu.getMenuId());
        BasicDBObject setValue = (BasicDBObject) MenuConvert.castMenuToDBObject(menu);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    /**
     * 删除视频分类信息
     * @param id
     */
    public void deleteMenuByid(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }

    /**
     * 查询视频分类的记录数
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countMenuByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 查询视频分类列表
     * @param orders 查询的排序条件
     * @param params 模糊查询的查询条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<Menu> getMenuListByParams(Map<String, Object> orders, Map<String, Object> params, Integer start, Integer limit) {

        List<Menu> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Menu menu = MenuConvert.castDBObjectToMenu(dbObject);
                result.add(menu);
            }
        } catch (Exception e) {
            logger.error("getMenuListByParams error !", e);
        }
        return result;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("menuName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("menuName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("menuName", pattern);
            }
            if (params.get("status") != null) {
                query.put("status", ObjectUtils.toInteger(params.get("status")));
            }
            if (params.get("type") != null) {
                query.put("type", ObjectUtils.toInteger(params.get("type")));
            }
        }
        return query;
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }

    public List<Menu> getMenuListByParams(Map<String, Object> orders, Map<String, Object> params) {

        List<Menu> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                Menu menu = MenuConvert.castDBObjectToMenu(dbObject);
                result.add(menu);
            }
        } catch (Exception e) {
            logger.error("getMenuListByParams error !", e);
        }
        return result;
    }


}
